package com.gdut.sport.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class HistoryDao {

    public static List<History> getHistoryList(Context context) {
        List<History> list = new ArrayList<>();
        DBOpenHelper helper = new DBOpenHelper(context);
        SQLiteDatabase db = helper.getReadableDatabase();
        final String sql = "select * from history order by createdAt desc";
        Cursor cursor = db.rawQuery(sql, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                History history = new History();
                history.setId(cursor.getInt(cursor.getColumnIndex("id")));
                history.setDistance(cursor.getDouble(cursor.getColumnIndex("distance")));
                history.setTime(cursor.getString(cursor.getColumnIndex("time")));
                history.setCreatedAt(cursor.getString(cursor.getColumnIndex("createdAt")));
                list.add(history);
            }
            cursor.close();
        }
        db.close();
        return list;
    }

    public static void add(Context context, History history) {
        DBOpenHelper helper = new DBOpenHelper(context);
        SQLiteDatabase db = helper.getWritableDatabase();
        final String sql = "insert into history(distance,time,createdAt) values(?,?,?)";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        db.execSQL(sql, new Object[]{history.getDistance(), history.getTime(), sdf.format(new Date())});
        db.close();
    }

    public static void delete(Context context, History history) {
        DBOpenHelper helper = new DBOpenHelper(context);
        SQLiteDatabase db = helper.getWritableDatabase();
        db.delete("history", "id=?", new String[]{String.valueOf(history.getId())});
        db.close();
    }

}
